using Infrastructure.Attribute;
using Infrastructure.Extensions;
using ZR.Model.BaseManage.Dto;
using ZR.Model.BaseManage;
using ZR.Repository;
using ZR.Service.BaseManage.IBaseManageService;
using Infrastructure;

namespace ZR.Service.BaseManage
{
    /// <summary>
    /// 供应商信息Service业务层处理
    /// </summary>
    [AppService(ServiceType = typeof(IBaseSupplierService), ServiceLifetime = LifeTime.Transient)]
    public class BaseSupplierService : BaseService<BaseSupplier>, IBaseSupplierService
    {
        /// <summary>
        /// 查询供应商信息列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public PagedInfo<BaseSupplierDto> GetPageList(BaseSupplierQueryDto parm)
        {
            var predicate = QueryExp(parm);

            var response = Queryable()
                .Where(predicate.ToExpression())
                .ToPage<BaseSupplier, BaseSupplierDto>(parm);

            return response;
        }


        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="SupplierId"></param>
        /// <returns></returns>
        public BaseSupplier GetInfo(string SupplierId)
        {
            var response = Queryable()
                .Where(x => x.SupplierId == SupplierId)
                .First();

            return response;
        }

        /// <summary>
        /// 添加供应商信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public BaseSupplier AddBaseSupplier(BaseSupplier model)
        {
            if (this.Any(it => it.SupplierCode == model.SupplierCode))
            {
                throw new CustomException($"系统中已包含{model.SupplierCode}编码信息");
            }
            return Insertable(model).ExecuteReturnEntity();
        }

        /// <summary>
        /// 修改供应商信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateBaseSupplier(BaseSupplier model)
        {
            if (this.Any(it => it.SupplierCode == model.SupplierCode && it.SupplierId != model.SupplierId))
            {
                throw new CustomException($"系统中已包含{model.SupplierCode}编码信息");
            }
            return Update(model, true);
        }

        /// <summary>
        /// 查询导出表达式
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        private static Expressionable<BaseSupplier> QueryExp(BaseSupplierQueryDto parm)
        {
            var predicate = Expressionable.Create<BaseSupplier>();

            predicate = predicate.AndIF(!string.IsNullOrEmpty(parm.SupplierCode), it => it.SupplierCode == parm.SupplierCode);
            predicate = predicate.AndIF(!string.IsNullOrEmpty(parm.SupplierName), it => it.SupplierName == parm.SupplierName);
            predicate = predicate.AndIF(parm.Enabled != null, it => it.Enabled == parm.Enabled);
            return predicate;
        }
    }
}